package alg20250211;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Text {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        int n = nums.length;
        List<List<Integer>> ret = new ArrayList<>();
        for (int i = 0; i < n - 2; ) {
            for (int left = i + 1, right = n - 1; left < right; ) {
                int target = -nums[i];
                if(nums[left] + nums[right] > target) right--;
                else if(nums[left] + nums[right] < target) left++;
                else{
                    ret.add(new ArrayList<>(Arrays.asList(nums[left], nums[right], nums[i])));
                    left++; right--;
                    while(nums[left] == nums[left - 1] && left < right) left++;
                    while(nums[right] == nums[right + 1] && left < right) right--;
                }
            }
            i++;
            while(i < n - 2 && nums[i] == nums[i - 1]) i++;
        }
        return ret;
    }
}
